package com.weseal.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * @author weseal
 * @title 模拟发起http请求工具类
 * @description
 * @usage
 * @copyright Copyright 2014 RENRENMEIJU Corporation. All rights reserved.
 * @company 上海众多美网络科技有限公司
 * @create 2014-12-23 上午10:20:38
 */
public class HttpUtil {

	public static String doPost(String urlString, String paramData, Map<String, String> headParams) throws Exception {
		HttpURLConnection httpConn = null;

		try {
			URL url = new URL(urlString);
			httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			if (headParams != null && headParams.size() > 0) {
				for (String key : headParams.keySet()) {
					httpConn.setRequestProperty(key, headParams.get(key));
				}
			}

			OutputStream os = httpConn.getOutputStream();
			os.write(paramData.toString().getBytes()); // 往远程URL传递参数
			os.flush();
			os.close();

			int code = httpConn.getResponseCode();
			if (code == 200) { // 返回成功
				BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
				String line;
				StringBuffer buffer = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					buffer.append(line).append("\n");
				}
				reader.close();
				return buffer.toString();
			} else { // 访问失败
				//forward error page
				throw new Exception("Error occur when try to visit the url:" + url.getPath()
						+ " using HttpURLConnection");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpConn != null) {
				httpConn.disconnect();
			}
		}

		return null;
	}

	public static String doGet(String urlString, String paramData, Map<String, String> headParams) throws Exception {
		HttpURLConnection httpConn = null;

		try {
			URL url = new URL(urlString);
			httpConn = (HttpURLConnection) url.openConnection();

			httpConn.setRequestProperty("Accept-Charset", "utf-8");
			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			if (headParams != null && headParams.size() > 0) {
				for (String key : headParams.keySet()) {
					httpConn.setRequestProperty(key, headParams.get(key));
				}
			}

			httpConn.connect();
			int code = httpConn.getResponseCode();
			if (code == 200) { // 返回成功
				BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
				String line;
				StringBuffer buffer = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					buffer.append(line).append("\n");
				}
				reader.close();
				return buffer.toString();
			} else { // 访问失败
				//forward error page
				throw new Exception("Error occur when try to visit the url:" + url.getPath()
						+ " using HttpURLConnection");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpConn != null) {
				httpConn.disconnect();
			}
		}

		return null;
	}

	public static String getRemoteHost(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

	public static void main(String[] args) {
		try {
			doGet("http://g3.letv.cn/vod/v2/MTMzLzEyLzM1L2JjbG91ZC8xMjM5NjYvdmVyXzAwXzIyLTMxOTA0OTIyMC1hdmMtMjI5ODQzLWFhYy0xMjgwMDEtMjY0ODkzOC0xMjI1OTkzODMtNzkyNjRkNzZhYzdiNDdjZDczN2U4ODFjMmNlMzk3N2EtMTQzMTU3NDE2OTExNC5tcDQ=?b=370&mmsid=30750339&tm=1446171913&key=20ed092920f5ffe72d9449667c8168f2&platid=2&splatid=206&playid=0&tss=no&vtype=21&cvid=278226990760&payff=0&pip=fa8d4b3abefb9a0cea36f3a0f5fe52dc&tag=mobile&sign=bcloud_123966&termid=2&pay=0&ostype=android&hwtype=un",
					null, null);
		} catch (Exception e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}
}
